import os
import shutil
import re
import subprocess
import time

am_src = "cpu/am-kernels/tests/cpu-tests/build/"
riscv_tests_src = "cpu/riscv-tests/build/"
test_src = "cpu/testvector/testcopy.bin"
pc_src = "cpu/build/stop_pc.txt"

# to_src = am_src
to_src = riscv_tests_src
all_tests = os.listdir(to_src)
test_bins = list(filter(lambda x : ".bin" in x, all_tests))

# test_bins = ["recursion-riscv64-mycpu.bin"]

time_used = time.time()
for i in range(len(test_bins)):
    test_bin = test_bins[i]
    # print(test_bin)

    shutil.copyfile(to_src+(test_bin), test_src)

    p = os.popen("make verilator")
    # print(p.read())
    r_from_terminal = p.read()
    p.close()
    # p = subprocess.Popen("make verilator")
    # print(p.stdout.read())
    # p.close()

    with open(pc_src, 'r') as f:
        pc_stop = f.read()

    pc_stop = eval(pc_stop)

    with open(to_src+test_bin.replace(".bin", ".txt"), "r") as f:
        pc_real_stop = f.readlines()

    index = 0
    for i in range(len(pc_real_stop)):
        if (to_src == am_src):
            stop_str =  "<_trm_init>:"
        else:
            stop_str = "<halt>:"
        if stop_str in pc_real_stop[i]:
            index = i 
            # print(pc_real_stop[i])
            break
    if (to_src == am_src):
        pc_real_stop = pc_real_stop[index+6]
    else:
        pc_real_stop = pc_real_stop[index+1]
    pc_real_stop = re.split(r"[\s\t]+", pc_real_stop)[1]
    pc_real_stop = eval("0x"+pc_real_stop[:-1])
    if not ((pc_real_stop) == pc_stop):
        print("\n")
        print(test_bin)
        print(pc_stop)
        print("\n")
    elif to_src == riscv_tests_src:
        r_from_terminal = r_from_terminal.split("\n")
        for i in r_from_terminal:
            if "x10" in i:
                print(i)
            elif "is_stop" in i:
                print("is_stop")

time_used = time.time() - time_used
print("Total sim time: ", time_used)
